<template>
  <div>
    <!-- 物体旋转 -->
    <div ref="container" class="w-full h-screen bg-gray-100"></div>
  </div>
</template>

<script setup>
import { onMounted, ref } from "vue";
import * as THREE from "three";

onMounted(() => {
  init();
});

const container = ref(null);
let scene, camera, renderer, cube;
function init() {
  // 清除之前的场景
  if (scene) {
    scene.clear();
  }

  // 1.创建场景
  scene = new THREE.Scene();
  //   scene.background = new THREE.Color(0xffffff); // 设置背景颜色为白色

  const loader = new THREE.TextureLoader();
  loader.load(
    "https://file.supore.cn/1733456524微信图片_20240304170728.jpg",
    (texture) => {
      scene.background = texture; // 异步， 贴图
      // render.render(scene,camera); // 渲染  --如果没有循环，则需再次调用一下
    }
  );
  // 2.创建相机
  camera = new THREE.PerspectiveCamera(
    75, // FOV 摄像机视椎体垂直视野角度
    window.innerWidth / window.innerHeight, // 摄像机视椎体宽高比(长宽比)
    0.1, // near 摄像机视椎体近端面
    1000 // far 摄像机视椎体远端面
  );
  // 3.创建渲染器
  renderer = new THREE.WebGLRenderer();

  // 4.设置渲染器尺寸并添加到 DOM
  renderer.setSize(window.innerWidth, window.innerHeight);
  container.value.appendChild(renderer.domElement);

  // 5.创建一个立方体
  const geometry = new THREE.BoxGeometry(1, 1, 1);
  const material = new THREE.MeshBasicMaterial({ color: 0xbe77ff });
  cube = new THREE.Mesh(geometry, material);
  scene.add(cube);

  // 6.设置相机位置
  camera.position.z = 2;
  camera.lookAt(0, 0, 0);// 摄像机视点

  // 7.渲染循环
  function animate() {
    requestAnimationFrame(animate);

    // 使立方体旋转
    cube.rotation.x += 0.01;
    cube.rotation.y += 0.01;

    renderer.render(scene, camera);
  }

  animate();
}

// 窗口大小变化时重新调整渲染器尺寸
window.addEventListener("resize", () => {
  renderer.setSize(window.innerWidth, window.innerHeight);
  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();
});
</script>